<template>
  <div class="flex flex-col h-full">
    <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState">
        <a-form-item name="zjm" label="" class="w-64 mr-3">
          <a-input v-model:value="formState.zjm" allow-clear placeholder="销售单号/姓名/助记码/信息卡号" />
        </a-form-item>
        <a-form-item name="dateRange" label="配镜时间" class="w-72 mr-3">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="returnDateRange" label="退费时间" class="w-72 mr-3">
          <a-range-picker v-model:value="formState.returnDateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" allow-clear />
        </a-form-item>
        <a-form-item name="billingName" label="商品大类" class="w-64 mr-3">
          <a-select v-model:value="formState.payItemType" allow-clear placeholder="请选择">
            <a-select-option value="60">镜架费</a-select-option>
            <a-select-option value="61">镜片费</a-select-option>
            <a-select-option value="62">隐形眼镜</a-select-option>
            <a-select-option value="63">角膜塑形镜</a-select-option>
            <a-select-option value="64">设备费</a-select-option>
            <a-select-option value="65">视光其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="billingName" label="商品分类" class="w-64 mr-3">
          <!-- <a-select
            v-model:value="formState.categroyId"
            :options="categroyList"
            allow-clear
            placeholder="请选择"
            :field-names="{ label: 'categroyName', value: 'id' }"
          /> -->
          <a-tree-select
            v-model:value="formState.categroyId"
            :tree-data="categroyList"
            allow-clear
            placeholder="请选择"
            tree-node-filter-prop="pathName"
            :field-names="{
              label: 'categroyName',
              key: 'id',
              value: 'id'
            }"
            @select="onSelect"
          >
            <template v-if="loading" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-tree-select>
        </a-form-item>
        <a-form-item name="productZjm" label="商品" class="w-[250px] ml-2 mr-3">
          <a-input v-model:value="formState.productZjm" allow-clear placeholder="商品名称/助记码" />
        </a-form-item>
        <a-form-item name="billingName" label="开单人" class="w-64 mr-3">
          <a-input v-model:value="formState.billingName" allow-clear placeholder="请输入" />
        </a-form-item>
        <a-form-item name="handlerName" label="经手人" class="w-64 mr-3">
          <a-input v-model:value="formState.handlerName" allow-clear placeholder="请输入" />
        </a-form-item>
        <a-form-item name="doctorName" label="推荐医生" class="w-64 mr-3">
          <a-input v-model:value="formState.doctorName" allow-clear placeholder="请输入" />
        </a-form-item>
        <a-form-item name="opticianDoctorName" label="配镜医生" class="w-64 mr-3">
          <a-input v-model:value="formState.opticianDoctorName" allow-clear placeholder="请输入" />
        </a-form-item>
        <a-form-item class="ml-4">
          <a-radio-group v-model:value="formState.isOutside">
            <a-radio value="">全部</a-radio>
            <a-radio value="1">外购</a-radio>
            <a-radio value="0">非外购</a-radio>
          </a-radio-group>
          <!-- <a-checkbox v-model:checked="formState.isOutside">包含外购定制</a-checkbox> -->
        </a-form-item>
        <a-form-item name="isTf" class="ml-5">
          <a-radio-group v-model:value="formState.isTf">
            <a-radio value="">全部</a-radio>
            <a-radio value="SF">收费</a-radio>
            <a-radio value="TF">退费</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="outStorageStatus" label="出库状态" class="ml-5">
          <a-radio-group v-model:value="formState.outStorageStatus">
            <a-radio value="">全部</a-radio>
            <a-radio value="0">未出库</a-radio>
            <a-radio value="1">已出库</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-end mb-2">
        <BaseExport type="视光" name="销售明细" code="000265" :search-params="{ ...formState }">导出</BaseExport>
      </div>
      <BaseTable
        fill
        bordered
        column-code="000265"
        :extra-height="50"
        :loading="loading"
        :scroll="{ x: 2500 }"
        :data-source="tableData"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex == 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <MedicineInfo :value="{ mc: record.mc, gg: record.gg }" />
          </template>
          <template v-if="column.dataIndex === 'zzcf'">
            <!-- 1：远用 2：近用 -->
            <a-tooltip placement="topLeft">
              <template #title
                >{{ record.longOrShort === '1' ? '远用' : '近用' }}<br />
                {{ record.zzcfyy }}<br />
                {{ record.zzcfzy }}</template
              >
              <span class="cursor-pointer"
                >{{ record.longOrShort === '1' ? '远用' : '近用' }}
                {{ record.zzcfyy }}
                {{ record.zzcfzy }}</span
              >
            </a-tooltip>
          </template>
          <!-- <template v-if="column.dataIndex === 'id'">
            <PopoverTable :config="detailConfig" :params="{ id: record.id }" :width="1600">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'isOutside'">
                  <div>{{ popRecord.isOutside === '1' ? '是' : '否' }}</div>
                </template>
              </template>
              {{ record.id }}
            </PopoverTable>
          </template> -->
          <!-- <template v-if="column.dataIndex === 'downPaymentAmount1'">
            <div v-if="record.chargeDepositStatus === '1'">{{ record.downPaymentAmount }}</div>
            <div v-else>0</div>
          </template> -->
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <template v-for="column in columnsData" :key="column.dataIndex">
                <a-table-summary-cell v-if="column.dataIndex === 'xh'"> 合计 </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'num'">
                  <div class="text-right">{{ summaryData.num || 0 }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'stock'">
                  <div class="text-right">{{ summaryData.stock || 0 }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'availableStock'">
                  <div class="text-right">{{ summaryData.availableStock || 0 }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else-if="column.dataIndex === 'payAmount'">
                  <div class="text-right">￥{{ formatAmount(summaryData.payAmount || 0) }}</div>
                </a-table-summary-cell>
                <a-table-summary-cell v-else>-</a-table-summary-cell>
              </template>
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { formatAmount } from '@/utils/format.js'

const formRef = ref(null)
const categroyList = ref([])
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  returnDateRange: [],
  status: false,
  isOutside: '',
  isTf: '',
  outStorageStatus: ''
})

//获取表头
const columnsData = ref([])
const getTableColumns = async () => {
  const { code, data } = await post('/common/util/getTableMappingCloumnList', { id: '000265' })
  if (code !== 0) return message.error(code)
  columnsData.value = data.filter((item) => !item.isHide)
}
const summaryData = ref({})
const getSummaryData = async () => {
  const { code, data } = await post('/optometry/ooadolescentcheck/opticalSalesOrderDetailsHj', {
    stdate: formState.value.dateRange[0],
    eddate: formState.value.dateRange[1],
    tfstdate: formState.value.returnDateRange?.[0],
    tfeddate: formState.value.returnDateRange?.[1],
    ...formState.value
  })
  if (code !== 0) return message.error(code)
  summaryData.value = data || {}
}

// const detailConfig = ref({
//   url: '/optometry/ooadolescentcheck/GetOoOpticianSubrecordeAllList',
//   columnCode: '000266',
//   rowKey: 'id',
//   formatResult: (data) => {
//     return data.map((item, index) => ({
//       ...item,
//       NO: index + 1
//     }))
//   }
// })

const { loading, tableData, pagination, getData } = useTable({
  url: '/optometry/ooadolescentcheck/OpticalSalesOrderDetails',
  immediate: true,
  params: formState.value,
  formatParams: (params) => {
    return {
      ...params,
      stdate: params['dateRange']?.[0],
      eddate: params['dateRange']?.[1],
      tfstdate: params['returnDateRange']?.[0],
      tfeddate: params['returnDateRange']?.[1]
    }
  },
  onSuccess: () => {
    getSummaryData()
  }
})
const getCategroyList = async () => {
  const { code, data } = await post('/operation/opex/getOoCategroyList', { status: 1 })
  if (code === 0) {
    categroyList.value = data
  }
}
// //递归获取所有子节点children获取id
// const dataManipulation = (data) => {
//   return data.map((item) => {
//     const childObjects = item.children && item.children.length > 0 ? dataManipulation(item.children) : []
//     return {
//       ...item,
//       children: childObjects
//     }
//   })
// }

onMounted(() => {
  getCategroyList()
  getTableColumns()
})
</script>
